# -*- coding: utf-8 -*-
import time, sys, os
from optparse import make_option
from enbook.games import EnLib
from django.core.management.base import BaseCommand
from django.core.exceptions import ObjectDoesNotExist
from enbook.games.models import Domains, Games
from enbook.games import Loader

# Модуль загрузки сценариев игр. 
DISABLED_SCENARIO_FILESIZE = 3500

class Command(BaseCommand):
    help = 'Downloads games\' scenarios from EN domains'
    option_list = BaseCommand.option_list + (
        make_option('--checkabsent', default=False, action='store_true',
            help=u'Force to check scenarios marked as "not available" for availability.'),
        make_option('--verbose', default=False, action='store_true',
            help=u'Show progress messages.'),
        make_option('--domain', default=None, action='store', type="string",
            help=u'process only provided domain'),
        make_option('--recheck', default=False, action='store_true',
            help=u'Force to check scenarios marked as "available" but with "no permissions" in content.'),
    )

    def storeScenario(self,game, domain, text):
        cdate = time.strftime("%Y-%m-%d %H:%M:%S")
        textLen = len(text)
        scenarioPath = EnLib.makeGamePath(domain, game.id) + '%s_scenario.html' % (game.id,)
        file = open(scenarioPath,'w',0755)
        if file:
            file.write(text)
            file.close()
            cdate = time.strftime("%Y-%m-%d %H:%M:%S")
            if textLen < DISABLED_SCENARIO_FILESIZE:      # Если размер сценария меньше 3500 байт, то почти наверняка сценарий недоступен
                game.has_scenario = 0    # Сценарий не доступен, сообщение загружено
            else:
                game.has_scenario = 1    # Сценарий загружен и доступен
            game.scenario_updated = cdate
            game.save()

    def handle(self, *args, **options):
        """
            Точка входа при выполнении команды
        """
        verbose = options.get('verbose',False)
        EnLib.checkFileStorage()
        checkabsent = options.get('checkabsent',False)
        domain = options.get('domain', None)

        if options.get('recheck', False):
            games = Games.objects.filter(has_scenario=1).select_related('domain')
            for game in games:
                scenarioPath = EnLib.makeGamePath(game.domain.domain_name, game.id) + '%s_scenario.html' % (game.id,)
                if os.path.exists(scenarioPath):
                    if os.stat(scenarioPath).st_size < DISABLED_SCENARIO_FILESIZE:
                        game.has_scenario = 0
                        game.save()
                        print game.id,game.domain, ' disabled'
            return
        
        if verbose and checkabsent: print 'Will check only absent scenarios...'
        if verbose and domain: print 'Check for scenarios of "%s" domain only' % (domain,)

        if checkabsent:
            scenario_filter = 0
        else:
            scenario_filter = -1

        if domain:
            games = Games.objects.select_related('domain').filter(has_scenario=scenario_filter, domain__domain_name=domain).order_by('id')
        else:
            games = Games.objects.filter(has_scenario=scenario_filter).select_related('domain').order_by('domain','id')
        
        if verbose: print "Will load %d scenarios" %len(games)
        
        for game in games:
            domain = game.domain.domain_name
            if verbose: print "\n %s gid: %s ..." % (domain,game.id),
            text = Loader.getScenarioSource(domain,game.id)
            self.storeScenario(game, domain, text)
            if verbose: print "saved"
